package com.lwl.concurrency.synchr;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadLocalRandom;

/**
 * 计数器,通常用于控制线程等待,等到计数器由指定的数减为0,则线程继续向下执行
 *
 * @author liwenlong - 2018/3/28 13:48
 */
public class CountDownLatchDemo {
    static CountDownLatch countDownLatch = new CountDownLatch(5);

    public void run() {
        try {
            Thread.sleep(ThreadLocalRandom.current().nextInt(10) * 1000);
            System.out.println(Thread.currentThread().getName() + " complete");
            countDownLatch.countDown();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        CountDownLatchDemo demo = new CountDownLatchDemo();
        ExecutorService executorService = Executors.newFixedThreadPool(10);
        for (int i = 0; i < 10; i++) {
            executorService.submit(demo::run);
        }
        countDownLatch.await();
        System.out.println("all thread completed");
        executorService.shutdown();
    }


}
